package com.pang.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pang.common.utils.PageUtils;
import com.pang.common.utils.Query;
import com.pang.gulimall.product.dao.CategoryDao;
import com.pang.gulimall.product.entity.CategoryEntity;
import com.pang.gulimall.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public List<CategoryEntity> queryAllWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> collect =
                categoryEntities
                        .stream()
                        .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                        .map(categoryEntity -> {
                            categoryEntity.setChildren(getChildrenMenu(categoryEntity, categoryEntities));
                            return categoryEntity;
                        })
                        .sorted((categoryEntityA, categoryEntityB) ->
                                Optional.ofNullable(categoryEntityA.getSort()).orElse(0).intValue()
                                        - (categoryEntityB.getSort() == null ? 0 : categoryEntityB.getSort()))
                        .collect(Collectors.toList());

        return collect;
    }

    public List<CategoryEntity> getChildrenMenu(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrenMenu(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((categoryEntityA, categoryEntityB) ->
                        Optional.ofNullable(categoryEntityA.getSort()).orElse(0).intValue()
                                - (categoryEntityB.getSort() == null ? 0 : categoryEntityB.getSort()))
                .collect(Collectors.toList());

    }


}